package com.fulihui.weixinsdk.http;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.HashMap;
import java.util.Map;

/**
 * http请求方式 选择器 使用需要注册到spring
 * Created by LeeSon on 2017/3/30 0030.
 */
public class HttpSelector {
    private static final Logger logger = LoggerFactory.getLogger(HttpSelector.class);
    /**
     * 最大连接数
     */
    private int maxTotal = 500;
    /**
     * 单路由最大连接数
     */
    private int maxRoute = 100;
    /**
     * 证书地址
     */
    private String certFile;
    /**
     * 证书密码
     */
    private String certPwd;

    Map<HttpRequestType, HttpInvoke> HTTP_TYPE_MAP = new HashMap<>();

    @PostConstruct
    public void init() {
        HTTP_TYPE_MAP.put(HttpRequestType.HTTP, new SimpleHttpClient(maxTotal, maxRoute));
        HTTP_TYPE_MAP.put(HttpRequestType.MULTIPART_HTTP, new MultipartHttpClient(maxTotal, maxRoute));
        if (StringUtils.isNotBlank(certFile) || StringUtils.isNotBlank(certPwd)) {
            HTTP_TYPE_MAP.put(HttpRequestType.HTTPS, new SslHttpClient(maxTotal, maxRoute, certFile, certPwd));
        }
        logger.info("HttpSelector init complete.");
    }

    @PreDestroy
    public void destroy() {
        HTTP_TYPE_MAP.forEach((k, v) -> {
            v.close();
        });
    }

    public HttpInvoke client(HttpRequestType type) {
        HttpInvoke client = HTTP_TYPE_MAP.get(type);
        if (null == client) {
            throw new RuntimeException("HttpSelector type is not register.");
        }
        return client;
    }

    public void setMaxTotal(int maxTotal) {
        this.maxTotal = maxTotal;
    }

    public void setMaxRoute(int maxRoute) {
        this.maxRoute = maxRoute;
    }

    public void setCertFile(String certFile) {
        this.certFile = certFile;
    }

    public void setCertPwd(String certPwd) {
        this.certPwd = certPwd;
    }
}